﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Forms;
using VAdvantage.Common;
using VAdvantage.Classes;
using VAdvantage.Model;
using VAdvantage.Utility;
using System.Data;
using VAdvantage.Controls;
using System.Windows.Markup;
using System.IO;
using System.Windows.Media.Imaging;
using System.Reflection;
using System.Collections;
using System.Runtime.InteropServices.Automation;
using VAdvantage.Logging;

namespace VAdvantage.Framework
{
    /// <summary>
    /// A window used to upload/download/view/delete attachments of a record
    /// </summary>
    public partial class AttachmentForm : ChildWindow
    {
        #region Private Variables
        // Window No
        private int _windowNo;
        // Attachment
        private MAttachment _attachment;
        // Change
        private bool _change = false;
        // Context
        private Context _ctx = VAdvantage.Utility.Envs.GetContext();
        // Form's initial height, width
        private int _height, _width;

        //mail attachment
        private MMailAttachment1 _mattachment;
        private int _AD_Table_ID;

        private int _Record_ID;
        //VImage image = new VImage();//silverlight comment
        //Image image = new Image();

        #endregion

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="windowNo">window number</param>
        /// <param name="AD_Attachment_ID">AD_Attachment_ID</param>
        /// <param name="AD_Table_ID">AD_Table_ID</param>
        /// <param name="Record_ID">Record_ID</param>
        /// <param name="trxName">transaction</param>
        public AttachmentForm(int windowNo, int AD_Attachment_ID, int AD_Table_ID, int Record_ID, string trxName)
        //: base(true, true, true, false, Msg.GetMsg(Envs.GetContext(), "Attachment", true))
        {
            base.Title = Msg.GetMsg(Envs.GetContext(), "Attachment", true);
            InitializeComponent();
            _AD_Table_ID = AD_Table_ID;
            _Record_ID = Record_ID;
            _windowNo = windowNo;
            _height = Util.GetValueOfInt(this.Height);
            _width = Util.GetValueOfInt(this.Width);
            LayoutRoot.Background = new SolidColorBrush(DataBase.GlobalVariable.WINDOW_BACK_COLOR);
            ToolTipService.SetToolTip(ibtnDeleteAll, Msg.GetMsg(Envs.GetContext(), "DeleteRecord", true));
            ToolTipService.SetToolTip(ibtnDelete, Msg.GetMsg(Envs.GetContext(), "DeleteRecord", true));
            ToolTipService.SetToolTip(ibtnLoad, Msg.GetMsg(Envs.GetContext(), "Load", true));
            ToolTipService.SetToolTip(ibtnOpen, Msg.GetMsg(Envs.GetContext(), "Open", true));
            ToolTipService.SetToolTip(ibtnSave, Msg.GetMsg(Envs.GetContext(), "AttachmentSave", true));
            ToolTipService.SetToolTip(btnCancel, Msg.GetMsg(Envs.GetContext(), "Cancel", true));
            ToolTipService.SetToolTip(btnOk, Msg.GetMsg(Envs.GetContext(), "Ok", true));
            lblComment.Content = Msg.GetMsg(Envs.GetContext(), "Comments", true);
            lblAttached.Content = Msg.GetMsg(Envs.GetContext(), "AttachedFiles", true); //Msg.GetMsg(Envs.GetContext(),"Attachments", true);
            btnOk.Click += new RoutedEventHandler(btnOk_Click);
            btnCancel.Click += new RoutedEventHandler(btnCancel_Click);
            //tabItem1.Text = Msg.GetMsg(Env.GetCtx(), "Attachment");//silverlight Comment
            //tabPage2.Text = Msg.GetMsg(Env.GetCtx(), "SentMailAttachment");//silverlight Comment
            //tabPage3.Text = Msg.GetMsg(Env.GetCtx(), "LetterAttachments");//silverlight Comment
            //CommonFunctions.SetTabProperties(vTabControl1);//silverlight Comment
            //InitialFormSetting.SetFont(this);//silverlight Comment
            vlblInfo.Content = "";
            //CommonFunctions.SetCmboBoxPrperties(vcmbFileNames);
            vtxtDesc.Focus();

            string strApp = "SELECT AppointmentsInfo_ID, Subject,Location,Description, " +
                               " ( " +
                               " CASE Label " +
                               "   WHEN 1   " +
                               "  THEN  '" + Msg.GetMsg(Envs.GetCtx(), "Important", true) + "' " +
                               "   WHEN 2 " +
                               "   THEN '" + Msg.GetMsg(Envs.GetCtx(), "Business", true) + "' " +
                               "   WHEN 3 " +
                               "   THEN   '" + Msg.GetMsg(Envs.GetCtx(), "Personal", true) + "' " +
                               "   WHEN 4 " +
                               "   THEN '" + Msg.GetMsg(Envs.GetCtx(), "Vacation", true) + "' " +
                               "   WHEN 5 " +
                               "   THEN '" + Msg.GetMsg(Envs.GetCtx(), "MustAttend", true) + "' " +
                               "   WHEN 6 " +
                               "   THEN '" + Msg.GetMsg(Envs.GetCtx(), "TravelRequired", true) + "' " +
                               "   WHEN 7 " +
                               "   THEN '" + Msg.GetMsg(Envs.GetCtx(), "NeedsPreparation", true) + "' " +
                               "   WHEN 8 " +
                               "   THEN '" + Msg.GetMsg(Envs.GetCtx(), "BirthDay", true) + "' " +
                               "   WHEN 9 " +
                               "   THEN '" + Msg.GetMsg(Envs.GetCtx(), "Anniversary", true) + "' " +
                               "   WHEN 10 " +
                               "   Then '" + Msg.GetMsg(Envs.GetCtx(), "PhoneCall", true) + "' " +
                               "   ELSE '" + Msg.GetMsg(Envs.GetCtx(), "None", true) + "' " +
                               " END ) AS label , " +
                               " StartDate ,  EndDate, " +
                               " ( " +
                               " CASE AllDay " +
                               "   WHEN 'Y' " +
                                "       THEN '" + Msg.GetMsg(Envs.GetCtx(), "Yes", true) + "' " +
                               "       ELSE '" + Msg.GetMsg(Envs.GetCtx(), "No", true) + "' " +
                               " END) AS Allday , " +
                               " ( " +
                               " CASE Status " +
                               "   WHEN 1 " +
                               "   THEN '" + Msg.GetMsg(Envs.GetCtx(), "Tentative", true) + "'  " +
                               "   WHEN 2 " +
                               "   THEN '" + Msg.GetMsg(Envs.GetCtx(), "Busy", true) + "' " +
                               "   WHEN 3 " +
                               "   THEN '" + Msg.GetMsg(Envs.GetCtx(), "OutOfOffice", true) + "' " +
                               "   Else " +
                               "    '" + Msg.GetMsg(Envs.GetCtx(), "Free", true) + "' " +
                               "    End) as Status, " +
                               "     ReminderInfo , AttendeeInfo,  RecurrenceInfo , " +
                               "     (  " +
                               "     CASE IsPrivate " +
                               "       WHEN 'Y' " +
                               "       THEN '" + Msg.GetMsg(Envs.GetCtx(), "Yes", true) + "' " +
                               "       ELSE '" + Msg.GetMsg(Envs.GetCtx(), "No", true) + "' " +
                               "     END) AS IsPrivate " +
                               "   FROM AppointmentsInfo WHERE record_Id =" + _Record_ID + " And Ad_Table_Id = " + _AD_Table_ID + " And AD_User_ID = " + _ctx.GetAD_User_ID();
            
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
            {
                //	Create Model
                if (AD_Attachment_ID == 0)
                {
                    _attachment = new MAttachment(_ctx, AD_Table_ID, Record_ID, trxName);
                }
                else
                {
                    _attachment = new MAttachment(_ctx, AD_Attachment_ID, trxName);
                }
                /////////////fill grid////////////////////
                IDataReader idr = null;
                DataTable dtvdgv = null;
                DataTable dtvdgvInboxMail = null;
                DataTable dtvdgvLetterAttachment = null;
                DataTable dtstrApp = null;

                try
                {
                    //Send mail section
                    //SetGrid(vdgv);//silverlight comment
                    //string strSql = "select mailaddressfrom, mailaddress as " + Msg.GetMsg(Envs.GetContext(), "MailTo", true) + ",title as " + Msg.GetMsg(Envs.GetContext(), "Subject", true) + ",created as " + Msg.GetMsg(Envs.GetContext(), "Sent", true) + ",  isattachment, mailattachment1_id, ad_client_id, ad_org_id, ad_table_id, record_id, createdby, isactive, ismailsent from mailattachment1 where record_id=" + _Record_ID + " and attachmenttype='M' and ad_table_id=" + AD_Table_ID + " ORDER BY created desc";
                    string strSql = "select MAILADDRESSFROM, MAILADDRESS as " + Msg.GetMsg(Envs.GetContext(), "MAILTO", true) + ",TITLE as " + Msg.GetMsg(Envs.GetContext(), "SUBJECT", true) + ",CREATED as " + Msg.GetMsg(Envs.GetContext(), "SENT", true) + ",  ISATTACHMENT, MAILATTACHMENT1_ID, AD_CLIENT_ID, AD_ORG_ID, AD_TABLE_ID, RECORD_ID, CREATEDBY, ISACTIVE, ISMAILSENT from mailattachment1 where record_id=" + _Record_ID + " and attachmenttype='M' and ad_table_id=" + AD_Table_ID + " ORDER BY created desc";

                    idr = DataBase.DB.ExecuteReader(strSql);
                    dtvdgv = new DataTable();
                    dtvdgv.Load(idr);
                    idr.Close();

                    //Inbox mail section
                    //SetGrid(vdgvInboxMail);//silverlight comment
                    strSql = "select MAILADDRESSFROM, MAILADDRESS as " + Msg.GetMsg(Envs.GetContext(), "MAILTO", true) + ",TITLE as " + Msg.GetMsg(Envs.GetContext(), "SUBJECT", true) + ",DateMailReceived as " + Msg.GetMsg(Envs.GetContext(), "MailReceived", true) + ",created as " + Msg.GetMsg(Envs.GetContext(), "AttachedDate", true) + ",  ISATTACHMENT, MAILATTACHMENT1_ID, AD_CLIENT_ID, AD_ORG_ID, AD_TABLE_ID, RECORD_ID, CREATEDBY, ISACTIVE, ISMAILSENT from mailattachment1 where record_id=" + _Record_ID + " and attachmenttype='I' and ad_table_id=" + AD_Table_ID + " ORDER BY created desc";
                    idr = DataBase.DB.ExecuteReader(strSql);
                    dtvdgvInboxMail = new DataTable();
                    dtvdgvInboxMail.Load(idr);
                    idr.Close();

                    //Letter Attachment Section
                    //SetGrid(vdgvLetterAttachment);//silverlight comment
                    //string strSqlLetter = "select mailaddress as " + Msg.GetMsg(Envs.GetContext(), "Address", true) + ",title as " + Msg.GetMsg(Envs.GetContext(), "Subject", true) + ",created as " + Msg.GetMsg(Envs.GetContext(), "Sent", true) + ", textmsg, binarydata, mailattachment1_id, ad_client_id, ad_org_id, ad_table_id, record_id, createdby, isactive, ismailsent, updated, updatedby,attachmenttype from mailattachment1 where record_id=" + _Record_ID + " and attachmenttype='L' and ad_table_id=" + AD_Table_ID + " ORDER BY mailaddress";
                    strSql = "select TITLE as " + Msg.GetMsg(Envs.GetContext(), "SUBJECT", true) + ",CREATED as " + Msg.GetMsg(Envs.GetContext(), "SENT", true) + ", ISATTACHMENT, MAILATTACHMENT1_ID, AD_CLIENT_ID, AD_ORG_ID, AD_TABLE_ID, RECORD_ID, CREATEDBY, ISACTIVE, ISMAILSENT from mailattachment1 where record_id=" + _Record_ID + " and attachmenttype='L' and ad_table_id=" + AD_Table_ID + " ORDER BY mailattachment1_id";
                    idr = DataBase.DB.ExecuteReader(strSql);
                    dtvdgvLetterAttachment = new DataTable();
                    dtvdgvLetterAttachment.Load(idr);
                    idr.Close();

                    //CommonFunctions.SetDataGridPrperties(vdgvApp);//silverlight Comment
                    //vdgvApp.MultiSelect = false;//silverlight Comment
                    
                    idr = DataBase.DB.ExecuteReader(strApp);
                    dtstrApp = new DataTable();
                    dtstrApp.Load(idr);
                    idr.Close();
                    //vdgvApp.ColumnHeadersDefaultCellStyle.Font = new System.Drawing.Font(vdgvApp.Font, System.Drawing.FontStyle.Regular);//silverlight Comment
                }
                catch { }

                System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => LoadAttachments(dtvdgv,
                dtvdgvInboxMail,
                 dtvdgvLetterAttachment,
                 dtstrApp));
            });
            SetBusy(true,"Downloading .. Plese Wait ..");

            //this.pnlFile.Controls.Add(image);//Add image in wraper1 control//silverlight comment used in invokgrid
            // image.Visible = false;//silverlight comment used in invokgrid
        }

        private void GridColumns(DataGrid ctrl)
        {
           // ctrl.Columns.Clear();
          //  ctrl.ColumnWidth = new DataGridLength(0, DataGridLengthUnitType.Star);
           // ctrl.RowHeight = 35;
           // ctrl.HorizontalAlignment = HorizontalAlignment.Stretch;
           // ctrl.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
            //ctrl.ShowRowNumber = true;
            //vdgv.VerticalAlignment = VerticalAlignment.Stretch;
            if (ctrl.Name == "vdgv" || ctrl.Name == "vdgvInboxMail" || ctrl.Name == "vdgvLetterAttachment")
            {



                if (ctrl.Name == "vdgvLetterAttachment")
                {
                    DataGridTextColumn MAILADDRESSFROM = new DataGridTextColumn();
                    MAILADDRESSFROM.Header = Msg.GetMsg(Envs.GetCtx(), "From");
                    MAILADDRESSFROM.Binding = new System.Windows.Data.Binding("MAILADDRESSFROM");
                    MAILADDRESSFROM.IsReadOnly = true;
                    MAILADDRESSFROM.Visibility = Visibility.Collapsed;
                    ctrl.Columns.Add(MAILADDRESSFROM);

                    //MAILADDRESSFROM.Width = new DataGridLength(0);


                    DataGridTextColumn mailTo = new DataGridTextColumn();
                    mailTo.Header = Msg.GetMsg(Envs.GetCtx(), "To");
                    mailTo.Binding = new System.Windows.Data.Binding("MAILTO");
                    mailTo.IsReadOnly = true;
                    mailTo.Visibility = Visibility.Collapsed;
                    ctrl.Columns.Add(mailTo);
                   // mailTo.Width = new DataGridLength(0);
                  //  mailTo.Width = new DataGridLength(0, DataGridLengthUnitType.Star);
                }
                else
                {
                    DataGridTextColumn MAILADDRESSFROM = new DataGridTextColumn();
                    MAILADDRESSFROM.Header = Msg.GetMsg(Envs.GetCtx(), "From");
                    MAILADDRESSFROM.Binding = new System.Windows.Data.Binding("MAILADDRESSFROM");
                    MAILADDRESSFROM.IsReadOnly = true;
                    MAILADDRESSFROM.Visibility = Visibility.Visible;
                    ctrl.Columns.Add(MAILADDRESSFROM);
                    VLogger.Get().Info(MAILADDRESSFROM.Binding.Path.ToString());
                    VLogger.Get().Info(MAILADDRESSFROM.Binding.ToString());
                  //  MAILADDRESSFROM.Width = new DataGridLength(0, DataGridLengthUnitType.Auto);



                    DataGridTextColumn mailTo = new DataGridTextColumn();
                    mailTo.Header = Msg.GetMsg(Envs.GetCtx(), "To");
                    mailTo.Binding = new System.Windows.Data.Binding("MAILTO");
                    mailTo.IsReadOnly = true;
                    mailTo.Visibility = Visibility.Visible;
                    ctrl.Columns.Add(mailTo);
                    VLogger.Get().Info(mailTo.Binding.Path.ToString());
                    VLogger.Get().Info(mailTo.Binding.ToString());
                  //  mailTo.Width = new DataGridLength(0, DataGridLengthUnitType.Auto);
                }
                DataGridTextColumn Subject = new DataGridTextColumn();
                Subject.Header = Msg.GetMsg(Envs.GetCtx(), "Subject");
                Subject.Binding = new System.Windows.Data.Binding("SUBJECT");
                Subject.IsReadOnly = true;
                Subject.Visibility = Visibility.Visible;
                ctrl.Columns.Add(Subject);
                VLogger.Get().Info(Subject.Binding.Path.ToString());
                VLogger.Get().Info(Subject.Binding.ToString());
                VLogger.Get().Info("Subject Added");
               
              //  Subject.Width = new DataGridLength(0, DataGridLengthUnitType.Auto);

                if (ctrl.Name == "vdgv" || ctrl.Name=="vdgvLetterAttachment")
                {
                    DataGridTextColumn Sent = new DataGridTextColumn();
                    Sent.Header = Msg.GetMsg(Envs.GetCtx(), "Sent");
                    Sent.Binding = new System.Windows.Data.Binding("SENT");
                    Sent.IsReadOnly = true;
                    Sent.Visibility = Visibility.Visible;
               //     Sent.Width = new DataGridLength(0, DataGridLengthUnitType.Auto);
                    ctrl.Columns.Add(Sent);
                }
                else if (ctrl.Name == "vdgvInboxMail")
                {
                    DataGridTextColumn Sent = new DataGridTextColumn();
                    Sent.Header = Msg.GetMsg(Envs.GetCtx(), "Sent");
                    Sent.Binding = new System.Windows.Data.Binding("SENT");
                    Sent.IsReadOnly = true;
                    Sent.Visibility = Visibility.Collapsed;
                    ctrl.Columns.Add(Sent);
               //     Sent.Width = new DataGridLength(0);

                    DataGridTextColumn MailReceived = new DataGridTextColumn();
                    MailReceived.Header = Msg.GetMsg(Envs.GetCtx(), "MailReceivedOn");
                    MailReceived.Binding = new System.Windows.Data.Binding("MAILRECEIVED");
                    MailReceived.IsReadOnly = true;
                    MailReceived.Visibility = Visibility.Visible;
                    ctrl.Columns.Add(MailReceived);
                    VLogger.Get().Info(MailReceived.Binding.Path.ToString());
                    VLogger.Get().Info(MailReceived.Binding.ToString());
                //    MailReceived.Width = new DataGridLength(0, DataGridLengthUnitType.Auto);

                    DataGridTextColumn AttachedDate = new DataGridTextColumn();
                    AttachedDate.Header = Msg.GetMsg(Envs.GetCtx(), "AttachedDateOn");
                    AttachedDate.Binding = new System.Windows.Data.Binding("ATTACHEDDATE");
                    AttachedDate.IsReadOnly = true;
                    AttachedDate.Visibility = Visibility.Visible;
                    ctrl.Columns.Add(AttachedDate);
                    VLogger.Get().Info(AttachedDate.Binding.Path.ToString());
                    VLogger.Get().Info(AttachedDate.Binding.ToString());
                 //   AttachedDate.Width = new DataGridLength(0, DataGridLengthUnitType.Auto);
                }
            }
            if (ctrl.Name == "vdgvApp")
            {
               

                DataGridTextColumn Location = new DataGridTextColumn();
                Location.Header = Msg.GetMsg(Envs.GetCtx(), "Location");
                Location.Binding = new System.Windows.Data.Binding("LOCATION");
                Location.IsReadOnly = true;
                // Subject.Visibility = Visibility.Visible;
                ctrl.Columns.Add(Location);

                DataGridTextColumn Description = new DataGridTextColumn();
                Description.Header = Msg.GetMsg(Envs.GetCtx(), "Description");
                Description.Binding = new System.Windows.Data.Binding("DESCRIPTION");
                Description.IsReadOnly = true;
                // Subject.Visibility = Visibility.Visible;
                ctrl.Columns.Add(Description);

                DataGridTextColumn Label = new DataGridTextColumn();
                Label.Header = Msg.GetMsg(Envs.GetCtx(), "Label");
                Label.Binding = new System.Windows.Data.Binding("LABEL");
                Label.IsReadOnly = true;
                // Subject.Visibility = Visibility.Visible;
                ctrl.Columns.Add(Label);

                DataGridTextColumn StartDate = new DataGridTextColumn();
                StartDate.Header = Msg.GetMsg(Envs.GetCtx(), "StartDate");
                StartDate.Binding = new System.Windows.Data.Binding("STARTDATE");
                StartDate.IsReadOnly = true;
                // Subject.Visibility = Visibility.Visible;
                ctrl.Columns.Add(StartDate);

                DataGridTextColumn EndDate = new DataGridTextColumn();
                EndDate.Header = Msg.GetMsg(Envs.GetCtx(), "EndDate");
                EndDate.Binding = new System.Windows.Data.Binding("ENDDATE");
                EndDate.IsReadOnly = true;
                // Subject.Visibility = Visibility.Visible;
                ctrl.Columns.Add(EndDate);

                DataGridTextColumn Allday = new DataGridTextColumn();
                Allday.Header = Msg.GetMsg(Envs.GetCtx(), "Allday");
                Allday.Binding = new System.Windows.Data.Binding("ALLDAY");
                Allday.IsReadOnly = true;
                // Subject.Visibility = Visibility.Visible;
                ctrl.Columns.Add(Allday);

                DataGridTextColumn AppointmentsInfo_ID = new DataGridTextColumn();
                AppointmentsInfo_ID.Header = Msg.GetMsg(Envs.GetCtx(), "AppointmentsInfo");
                AppointmentsInfo_ID.Binding = new System.Windows.Data.Binding("APPOINTMENTSINFO_ID");
                AppointmentsInfo_ID.IsReadOnly = true;
                AppointmentsInfo_ID.Visibility = Visibility.Collapsed;
                ctrl.Columns.Add(AppointmentsInfo_ID);

                DataGridTextColumn Status = new DataGridTextColumn();
                Status.Header = Msg.GetMsg(Envs.GetCtx(), "Status");
                Status.Binding = new System.Windows.Data.Binding("STATUS");
                Status.IsReadOnly = true;
                Status.Visibility = Visibility.Collapsed;
                ctrl.Columns.Add(Status);


                DataGridTextColumn ReminderInfo = new DataGridTextColumn();
                ReminderInfo.Header = Msg.GetMsg(Envs.GetCtx(), "ReminderInfo");
                ReminderInfo.Binding = new System.Windows.Data.Binding("REMINDERINFO");
                ReminderInfo.IsReadOnly = true;
                ReminderInfo.Visibility = Visibility.Collapsed;
                ctrl.Columns.Add(ReminderInfo);

                DataGridTextColumn AttendeeInfo = new DataGridTextColumn();
                AttendeeInfo.Header = Msg.GetMsg(Envs.GetCtx(), "AttendeeInfo");
                AttendeeInfo.Binding = new System.Windows.Data.Binding("ATTENDEEINFO");
                AttendeeInfo.IsReadOnly = true;
                AttendeeInfo.Visibility = Visibility.Collapsed;
                ctrl.Columns.Add(AttendeeInfo);

                DataGridTextColumn RecurrenceInfo = new DataGridTextColumn();
                RecurrenceInfo.Header = Msg.GetMsg(Envs.GetCtx(), "RecurrenceInfo");
                RecurrenceInfo.Binding = new System.Windows.Data.Binding("RECURRENCEINFO");
                RecurrenceInfo.IsReadOnly = true;
                RecurrenceInfo.Visibility = Visibility.Collapsed;
                ctrl.Columns.Add(RecurrenceInfo);

                DataGridTextColumn IsPrivate = new DataGridTextColumn();
                IsPrivate.Header = Msg.GetMsg(Envs.GetCtx(), "IsPrivate");
                IsPrivate.Binding = new System.Windows.Data.Binding("ISPRIVATE");
                IsPrivate.IsReadOnly = true;
                IsPrivate.Visibility = Visibility.Collapsed;
                ctrl.Columns.Add(IsPrivate);

            }



           
            
                DataGridTextColumn ISATTACHMENT = new DataGridTextColumn();
                ISATTACHMENT.Header = Msg.GetMsg(Envs.GetCtx(), "isAttachment");
                ISATTACHMENT.Binding = new System.Windows.Data.Binding("ISATTACHMENT");
                ISATTACHMENT.IsReadOnly = true;
                ISATTACHMENT.Visibility = Visibility.Collapsed;
                // ISATTACHMENT.Width = new DataGridLength(0);
                ctrl.Columns.Add(ISATTACHMENT);
           
            DataGridTextColumn MAILATTACHMENT1_ID = new DataGridTextColumn();
            MAILATTACHMENT1_ID.Header = Msg.GetMsg(Envs.GetCtx(), "MailAttachment");
            MAILATTACHMENT1_ID.Binding = new System.Windows.Data.Binding("MAILATTACHMENT1_ID");
            MAILATTACHMENT1_ID.IsReadOnly = true;
            MAILATTACHMENT1_ID.Visibility = Visibility.Collapsed;
        //    MAILATTACHMENT1_ID.Width = new DataGridLength(0);
            ctrl.Columns.Add(MAILATTACHMENT1_ID);

            DataGridTextColumn AD_CLIENT_ID = new DataGridTextColumn();
            AD_CLIENT_ID.Header = Msg.Translate(Envs.GetCtx(), "Ad_Client_ID");
            AD_CLIENT_ID.Binding = new System.Windows.Data.Binding("AD_CLIENT_ID");
            AD_CLIENT_ID.IsReadOnly = true;
            AD_CLIENT_ID.Visibility = Visibility.Collapsed;
        //    AD_CLIENT_ID.Width = new DataGridLength(0);
            ctrl.Columns.Add(AD_CLIENT_ID);

            DataGridTextColumn AD_ORG_ID = new DataGridTextColumn();
            AD_ORG_ID.Header = Msg.Translate(Envs.GetCtx(), "Ad_Org_ID");
            AD_ORG_ID.Binding = new System.Windows.Data.Binding("AD_ORG_ID");
            AD_ORG_ID.IsReadOnly = true;
            AD_ORG_ID.Visibility = Visibility.Collapsed;
        //    AD_ORG_ID.Width = new DataGridLength(0);
            ctrl.Columns.Add(AD_ORG_ID);

            DataGridTextColumn AD_TABLE_ID = new DataGridTextColumn();
            AD_TABLE_ID.Header = Msg.Translate(Envs.GetCtx(), "Ad_Table_ID");
            AD_TABLE_ID.Binding = new System.Windows.Data.Binding("AD_TABLE_ID");
            AD_TABLE_ID.IsReadOnly = true;
            AD_TABLE_ID.Visibility = Visibility.Collapsed;
         //   AD_TABLE_ID.Width = new DataGridLength(0);
            ctrl.Columns.Add(AD_TABLE_ID);

            DataGridTextColumn RECORD_ID = new DataGridTextColumn();
            RECORD_ID.Header = Msg.Translate(Envs.GetCtx(), "Record_ID");
            RECORD_ID.Binding = new System.Windows.Data.Binding("RECORD_ID");
            RECORD_ID.IsReadOnly = true;
            RECORD_ID.Visibility = Visibility.Collapsed;
         //   RECORD_ID.Width = new DataGridLength(0);
            ctrl.Columns.Add(RECORD_ID);

            DataGridTextColumn CREATEDBY = new DataGridTextColumn();
            CREATEDBY.Header = Msg.Translate(Envs.GetCtx(), "Createby");
            CREATEDBY.Binding = new System.Windows.Data.Binding("CREATEDBY");
            CREATEDBY.IsReadOnly = true;
            CREATEDBY.Visibility = Visibility.Collapsed;
       //     CREATEDBY.Width = new DataGridLength(0);
            ctrl.Columns.Add(CREATEDBY);


            DataGridTextColumn ISACTIVE = new DataGridTextColumn();
            ISACTIVE.Header = Msg.Translate(Envs.GetCtx(), "IsActive");
            ISACTIVE.Binding = new System.Windows.Data.Binding("ISACTIVE");
            ISACTIVE.IsReadOnly = true;
            ISACTIVE.Visibility = Visibility.Collapsed;
      //      ISACTIVE.Width = new DataGridLength(0);
            ctrl.Columns.Add(ISACTIVE);


            DataGridTextColumn ISMAILSENT = new DataGridTextColumn();
            ISMAILSENT.Header = Msg.GetMsg(Envs.GetCtx(), "IsMailSent");
            ISMAILSENT.Binding = new System.Windows.Data.Binding("ISMAILSENT");
            ISMAILSENT.IsReadOnly = true;
            ISMAILSENT.Visibility = Visibility.Collapsed;
       //     ISMAILSENT.Width = new DataGridLength(0);
            ctrl.Columns.Add(ISMAILSENT);
        }

        private void CreateGraphicsColumn(DataGrid ctrl, DataTable dt)//private void CreateGraphicsColumn(VAdvantage.Controls.VDataGridView ctrl)
        {
            if (dt != null)
            {
                GridColumns(ctrl);
                ctrl.ItemsSource = dt.GetBindableData(new Connector());
                if (ctrl.Name != "vdgvApp")
                {
                    DataGridTemplateColumn imgColumn = new DataGridTemplateColumn();
                    //imgColumn.Header = Envs.LoadImageSource("Attachment16.gif");
                    imgColumn.CellTemplate = (DataTemplate)XamlReader.Load("<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><Image Source=\"/VAdvantage;component/Images/Attachment32.png\" Height=\"15\" Width=\"15\"/></DataTemplate>");
                   

                    //  imgColumn.CellTemplate = (DataT VLogger.Get().Info(mailTo.Binding.Path.ToString());emplate)XamlReader.Load("<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><Image Source=\"/VAdvantage;component/Images/Attachment16.png Height='10' Width='10'/></DataTemplate>");

                    // imgColumn = new BitmapImage(new Uri("Images/Attachment16.PNG", UriKind.Relative));
                    ctrl.Columns.Insert(0, imgColumn);
                    VLogger.Get().Info("image Column Added");
                    imgColumn.Width = new DataGridLength(0, DataGridLengthUnitType.Auto);
                }
            }
            else
            {
                ctrl.DataContext = dt;
            }
            
            //var dt1 = (DataTemplate)Resources["ThumbViewTemplate"];
            

           //Image treeIcon = Envs.GetImageIcon("Attachment16.gif");

           //DataGridViewImageColumn iconColumn = new DataGridViewImageColumn();
           //iconColumn.Image = treeIcon;
           //iconColumn.Name = "";
           //iconColumn.HeaderText = "";
           //iconColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells; ;
           ////iconColumn.Width = 20;
           //ctrl.Columns.Insert(0, iconColumn);

           //var myTemplateColumn = new DataGridTemplateColumn();
           //myTemplateColumn.Header = "ImageColumn";
           //myTemplateColumn.CellTemplate = (DataTemplate)XamlReader.Load("<DataTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><Image Source=\"http://diditwith.net/content_images/Dog_With_Santa.jpg\"/></DataTemplate>");
           //ctrl.Columns.Insert(0, myTemplateColumn);
        }

        /// <summary>
        /// Load attachments
        /// </summary>
        private void LoadAttachments(DataTable dtvdgv, DataTable dtvdgvInboxMail, DataTable dtvdgvLetterAttachment, DataTable dtstrApp)
        {
            //	Set Text/Description
            string msg = _attachment.GetTextMsg();
            if (msg == null)
            {
                vtxtDesc.Text = "";
            }
            else
            {
                vtxtDesc.Text = msg;
            }

            
            SetButtonEnable(ibtnDelete, false);
            SetButtonEnable(ibtnOpen, false);
            SetButtonEnable(ibtnSave, false);

            //	Set Combo
            int size = _attachment.GetEntryCount();
           
           chkFileSystem.IsChecked = _attachment.IsFileSystem();
           
            if (size < 1 || _attachment.GetAD_Attachment_ID()<1)
            {
                chkFileSystem.IsChecked = true;
            }

            vcmbFileNames.Items.Clear();
            for (int i = 0; i < size; i++)
            {
                // add fil names in dropdown
                vcmbFileNames.Items.Add(_attachment.GetEntryName(i));
            }
            if (size > 0)
            {
                //vcmbFileNames.SelectedIndex = 0;
                vcmbFileNames.SelectedIndex = size - 1;
                //DisplayData();
            }
            else
            {
                //displayData(0);
            }
            CreateGraphicsColumn(vdgv, dtvdgv);
            CreateGraphicsColumn(vdgvInboxMail, dtvdgvInboxMail);
            CreateGraphicsColumn(vdgvLetterAttachment, dtvdgvLetterAttachment);
            CreateGraphicsColumn(vdgvApp, dtstrApp);
          //  vdgvApp.DataContext = dtstrApp;
            //vdgvApp.Columns[0].Visible = false;//silver light comment
            //vdgvApp.Columns[0].Visibility = Visibility.Collapsed;//silver light comment
           
            //image.Visibility = System.Windows.Visibility.Collapsed;
            SetBusy(false);
        }

        /// <summary>
        /// Display the data
        /// </summary>
        private void DisplayData()
        {
            // get selected entry
            MAttachmentEntry entry = _attachment.GetEntry(vcmbFileNames.SelectedIndex);

            //	Reset UI
            //pbImage.Image = null;
            //pbImage.Visible = false;
            image.Visibility = System.Windows.Visibility.Collapsed;

            //	no attachment
            if (entry == null)
            {
                vlblInfo.Content = "-";
            }
            else
            {
                //Get image data
                byte[] fileData = entry.GetData();

                // enable the buttons
                SetButtonEnable(ibtnDelete, true);
                SetButtonEnable(ibtnOpen, true);
                SetButtonEnable(ibtnSave, true);
                vlblInfo.SetVisible(true);
                // set information
                vlblInfo.Content = entry.GetEntryInfo();

                // if file is an image, show it
                if (entry.IsGraphic())
                {
                    int length = fileData.Length / 1024;

                    //Initialize image variable
                    Image newImage;
                    //Read image data into a memory stream
                    using (System.IO.MemoryStream ms = new System.IO.MemoryStream(fileData, 0, fileData.Length))
                    {
                       // ms.Write(fileData, 0, fileData.Length);

                        BitmapImage b = new BitmapImage();
                        b.SetSource(ms);
                        image.Source = b;
                        //Set image variable value using memory stream.
                        // newImage = System.Drawing.Image.FromStream(ms, true);//silverlight comment
                    }

                    //set picture
                    // pbImage.Visible = false;
                    //pbImage.Image = newImage;
                    image.Visibility = System.Windows.Visibility.Visible;
                    //image.AutoSize = true;//silverlight
                    //image.Image = newImage;//silverlight
                    //vlblInfo.Visible = false;//replace with next line
                    vlblInfo.Visibility = Visibility.Collapsed;
                    vlblInfo.Content = "";

                    // set width of the window in case of large pic
                    //if (pbImage.Width > this.Width)
                    //{
                    //    this.Width = pbImage.Width;
                    //}
                    //// set height of window in case of large pic
                    //if (pbImage.Height > this.Height)
                    //{
                    //    this.Height = pnlBottom.Height + pbImage.Height + pnlAttachButton.Height;
                    //}
                }
                else
                {
                    // set original form size
                    if (this.Height != _height || this.Width != _width)
                    {
                        this.Width = _width;
                        this.Height = _height;
                        //this.CenterToScreen();
                    }
                }
            }
        }

        /// <summary>
        /// Sets enable disable Image of buttons
        /// </summary>
        /// <param name="ibtnObj">button</param>
        /// <param name="isEnabled">bool type true for enabling button, false for disable button and 
        /// null if dont want to enable or disable button</param>
        //private void SetButtonEnable(ImageButton ibtnObj, bool isEnabled)//Silver doesn't support
        private void SetButtonEnable(Button ibtnObj, bool isEnabled)
        {
            // set image if upload button
            if (ibtnObj == ibtnLoad)
            {
                if (isEnabled)
                {
                    //ibtnObj.Image = VAdvantage.Properties.Resources.upload;//Silver doesn't support

                }
                else
                {
                    //ibtnObj.Image = VAdvantage.Properties.Resources.upload_disabled;//Silver doesn't support
                }
            }
            // set image if delete button
            else if (ibtnObj == ibtnDelete)
            {
                if (isEnabled)
                {
                    //ibtnObj.Image = VAdvantage.Properties.Resources.delete_attachment;
                }
                else
                {
                    //ibtnObj.Image = VAdvantage.Properties.Resources.delete_disabled;
                }
            }
            // set image if download button
            else if (ibtnObj == ibtnSave)
            {
                if (isEnabled)
                {
                    //ibtnObj.Image = VAdvantage.Properties.Resources.download;
                }
                else
                {
                    //ibtnObj.Image = VAdvantage.Properties.Resources.download_disabled;
                }
            }
            // set image if read button
            else if (ibtnObj == ibtnOpen)
            {
                if (isEnabled)
                {
                    //ibtnObj.Image = VAdvantage.Properties.Resources.read;
                }
                else
                {
                    // ibtnObj.Image = VAdvantage.Properties.Resources.read_disabled;
                }
            }
            // enbale / disable button
            ibtnObj.IsEnabled = isEnabled;//Silver doesn't support
        }

        #region Event Section
        const int CHUNKSIZE = 40000;   // You can change this number
        private void ibtnLoad_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            byte[] dataA = null;
            // openFileDialog.Title = Msg.GetMsg(Envs.GetContext(), "AttachmentNew", true);//silverlight comment
            openFileDialog.Filter = "All files (*.*)|*.*";

            if ((bool)openFileDialog.ShowDialog())//if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                if (openFileDialog.File.Exists)//if (openFileDialog.CheckFileExists)
                {
                    int size = _attachment.GetEntryCount();

                    FileInfo f = openFileDialog.File;
                    Stream s = f.OpenRead();
                    //************If you need to read the file one chunk at a time, 
                    //************here is the code how you do it: 
                    //int chunkSize;
                    //while (s.Position > -1 && s.Position < s.Length)
                    //{
                    //    if (s.Length - s.Position >= CHUNKSIZE)
                    //        chunkSize = CHUNKSIZE;
                    //    else
                    //        chunkSize = (int)(s.Length - s.Position); // last chunk
                    //    byte[] fileBytes = new byte[chunkSize];
                    //    int byteCount = s.Read(fileBytes, 0, chunkSize); //Read the bytes in chunk, read will start from the end position of last read

                    //    // now you can deal with your bytes array fileBytes 
                    //}
                    //************
                    //I have dot on s.length
                    //using (BinaryReader br = new BinaryReader(s))
                    //{
                    //    dataA = br.ReadBytes(s.Length);
                    //}
                    dataA = ReadFully(s);
                    if (_attachment.AddEntry(openFileDialog.File.Name, dataA))//if (_attachment.AddEntry(openFileDialog.FileName))
                    {
                        LoadAttachments(null, null, null, null);
                        _change = true;
                    }
                }
            }
        }

        public static byte[] ReadFully(Stream input)
        {
            byte[] buffer = new byte[25 * 1024*1024];

            if (input.Length > buffer.Length)
            {
                //File size must be less than 25 MB
                ShowMessage.Warn("FileSizeLimit", true, "", "");
                return null;
            }
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                int offset = 0;
                while ((read = input.Read(buffer, offset, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }

        //public byte[] GetArray(Stream s, int maxSize)
        //{
        //    byte[] array = new byte[maxSize];
        //    s.Read(array, 0, (int)array.Length);
        //    s.Close();
        //    return array;
        //}

        private void ibtnSave_Click(object sender, RoutedEventArgs e)
        {

            int index = vcmbFileNames.SelectedIndex;
            if (_attachment.GetEntryCount() < index || index == -1)
                return;

            string fileName = vcmbFileNames.SelectedItem.ToString();// .Text;//uncomment it for silverlight
            // opens the save file dialog box
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            // set filter
            saveFileDialog.Filter = "All files (*.*)|*.*";
            // set file name
            saveFileDialog.DefaultFileName = fileName.Substring(0, fileName.IndexOf("."));//uncomment it for silverlight
            // set extension
            saveFileDialog.DefaultExt = fileName.Substring(fileName.LastIndexOf("."));
            // set title
            //saveFileDialog.Title = Msg.GetMsg(Envs.GetContext(), "AttachmentSave", true);//Uncomment it for silverlight
            // if user clicks on save button
            bool? result = saveFileDialog.ShowDialog(); 
            if(result != null && (bool)result)
            {
                Stream s = saveFileDialog.OpenFile();
                //MAttachmentEntry entry = _attachment.GetEntry(vcmbFileNames.SelectedIndex);
                // save the file to harddisk
                _attachment.SaveEntryFile(vcmbFileNames.SelectedIndex, saveFileDialog.SafeFileName);
                //Classes.ShowMessage.Info("Saved", true, "", "");//uncomment it for silverlight 
                _attachment.SaveEntryFile(vcmbFileNames.SelectedIndex, saveFileDialog.SafeFileName,s);
               
            }
        }

       private void ibtnOpen_Click(object sender, RoutedEventArgs e)
        {

            //MessageBox.Show(System.IO.Path.GetTempPath());
            int index = vcmbFileNames.SelectedIndex;
            // get data
            byte[] data = _attachment.GetEntryData(index);

            if (data != null)
            {
                try
                {
                    // get temp folder path
                    string tempFilePath = System.IO.Path.GetTempPath() + _attachment.GetEntryName(index);
                    // save the file in temp folder
                    _attachment.SaveEntryFile(index, tempFilePath);
                    //silverlight comment*********************
                    // opens the file from temporary folder
                    dynamic cmd = AutomationFactory.CreateObject("WScript.Shell");
                    cmd.Run("calc.exe", 1, true);

                    //System.Diagnostics.pr .Process p = new System.Diagnostics.Process();
                    //System.Diagnostics.ProcessStartInfo ps = new System.Diagnostics.ProcessStartInfo(tempFilePath);
                    //p.StartInfo = ps;
                    //p.Start();
                    //*****************
                }
                catch (Exception ex)
                {
                    //Classes.ShowMessage.Error("Error", true, ex.ToString());
                }
            }
        }

        private void ibtnDelete_Click(object sender, RoutedEventArgs e)
        {
            int index = vcmbFileNames.SelectedIndex;
            // check any file exists in dropdown

            if (vcmbFileNames.SelectedItem == null)
                return;

            string fileName = vcmbFileNames.SelectedItem.ToString();// "";// vcmbFileNames.Text;//uncomment vcmbFileNames.Text for silverlight
            if (fileName == null || fileName.Trim() == "")
            {
                return;
            }

            ShowMessage.AskMessage("AttachmentDeleteEntry?", true, fileName, "").Closed += (sc, ec) =>
               {
                   if (true.Equals(((Message)sc).DialogResult))
                   {
                       SetBusy(true);
                       if (_attachment.DeleteEntry(index))
                       {
                           // remove from the dropdown
                           vcmbFileNames.Items.RemoveAt(index);
                           //pbImage.Image = null;
                           //image.Image = null;//silverlight comment
                           vlblInfo.Content = "-";
                           // load attachments
                           LoadAttachments(null, null, null, null);
                       }
                       _change = true;
                       SetBusy(false);
                   }
               };
        }

       private void ibtnDeleteAll_Click(object sender, RoutedEventArgs e)
        {

            //if (ShowMessage.Ask("AttachmentDelete?", true, ""))
            ShowMessage.AskMessage("AttachmentDelete?", true, "", "").Closed += (sc, ec) =>
              {
                  if (true.Equals(((Message)sc).DialogResult))
                  {
                      SetBusy(true,"Deleting");
                      System.Threading.ThreadPool.QueueUserWorkItem(delegate
                      {
                          _attachment.Delete(true);

                          Dispatcher.BeginInvoke(delegate
                          {
                              SetBusy(false);
                              this.DialogResult = false;
                          });
                      });
                  }
              };
        }

        void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        void btnOk_Click(object sender, RoutedEventArgs e)
        {
            // get the description entered by user
            bool oldCheck = _attachment.IsFileSystem();
            bool newCheck = chkFileSystem.IsChecked.Value;
            string newText = vtxtDesc.Text.Trim();
            if (newText == null)
                newText = "";
            // get previous description
            string oldText = _attachment.GetTextMsg();
            if (oldText == null)
                oldText = "";
            if (!_change)
            {
                _change = !newText.Equals(oldText);
            }
            if (!_change)
                _change = !oldCheck.Equals(newCheck);
            System.Threading.ThreadPool.QueueUserWorkItem(delegate
                    {
                        bool retVal = false;
                        if (newText.Length > 0 || _attachment.GetEntryCount() > 0)
                        {
                            // if any changes are made then save them
                            if (_change)
                            {
                                // set text message
                                _attachment.SetTextMsg(newText);
                                _attachment.SetIsFileSystem(newCheck);
                                // final save
                               retVal =  _attachment.Save();
                            }
                        }
                        else
                        {
                            // if no text message and no attachments, then delete the whole attachment
                          retVal =  _attachment.Delete(true);
                        }
                        if (retVal)
                        {
                            Deployment.Current.Dispatcher.BeginInvoke(() => CloseDialoge(true));
                        }
                        else
                        {
                            Deployment.Current.Dispatcher.BeginInvoke(() => SetBusy(false));
                        }
                    });
            SetBusy(true,"UploadingPleaseWait");
        }
        public void CloseDialoge(bool result)
        {
            SetBusy(false);
            this.DialogResult = result;
        }

        private void vcmbFileNames_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            DisplayData();
        }

        #endregion

        private void busyWindow_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true;
        }

        private void SetBusy(bool isBusy, string msg)
        {
            this.Cursor = isBusy ? Cursors.Wait : Cursors.Arrow;
            busyWindow.Visibility = isBusy ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            if (isBusy)
            {
                txtBusy.Text = Msg.GetMsg(Utility.Envs.GetCtx(), msg ?? "Processing");
            }
            else
            {
                txtBusy.Text = "";
            }
        }


        private void SetBusy(bool isBusy)
        {
            SetBusy(isBusy, null);   
        }


        DataGrid vdgvRecords = null;
        private void VImage_Click(object sender, RoutedEventArgs e)
        {


            SLControls.Controls.VImage btn = (SLControls.Controls.VImage)sender as SLControls.Controls.VImage;
            
            if(btn.Name=="btninbox")
            {
                vdgvRecords = vdgvInboxMail;
            }
            if(btn.Name=="btnSent")
            {
                vdgvRecords = vdgv;
            }
            if(btn.Name=="btnLetter")
            {
                vdgvRecords = vdgvLetterAttachment;
            }
            if (btn.Name == "btnAppointment")
            {
                IList rowSource = vdgvApp.ItemsSource as IList;
                if (vdgvApp.SelectedIndex != -1)
                {
                    // if (vdgvApp.Rows[e.RowIndex].Cells[0].Value != null || vdgvApp.Rows[e.RowIndex].Cells[0].Value != DBNull.Value)
                    if (((BindableObject)rowSource[vdgvApp.SelectedIndex]).GetValue("APPOINTMENTSINFO_ID") != null)
                    {
                        new Scheduler.AppointmentForm(int.Parse(((BindableObject)rowSource[vdgvApp.SelectedIndex]).GetValue("APPOINTMENTSINFO_ID"))).Show();

                        //new VAdvantage.Scheduler.cAppointment(Convert.ToInt32(vdgvApp.CurrentRow.Cells[0].Value));
                    }
                }

            }
            else
            {
                IList rosource = vdgvRecords.ItemsSource as IList;
                if (vdgvRecords.SelectedIndex == -1)
                {
                    ShowMessage.Info("PlsSelectRecord", true, "", "");
                    return;
                }




                int Id = Util.GetValueOfInt(((BindableObject)rosource[vdgvRecords.SelectedIndex]).GetValue("MAILATTACHMENT1_ID"));

                System.Threading.ThreadPool.QueueUserWorkItem(delegate
                {

                    if (Id == 0)
                    {
                        _mattachment = new MMailAttachment1(_ctx, _AD_Table_ID, _Record_ID, null);
                    }
                    else
                    {
                        _mattachment = new MMailAttachment1(_ctx, Id, null);
                    }
                    Dispatcher.BeginInvoke(delegate
                    {
                        if (btn.Name == "btnLetter")
                        {
                            VAdvantage.Framework.Email letter = new Email(_ctx, Msg.GetMsg(_ctx, "Letter"), _mattachment);
                            this.Close();
                            Utility.Envs.RegisterWindowForm(letter);
                            Envs.ShowForm(letter);
                        }
                        else
                        {
                            // MailBox.ShowMailMessage oShowMailMsg = new VAdvantage.MailBox.ShowMailMessage(_mattachment);
                            //oShowMailMsg.ShowDialog();
                            VAdvantage.Framework.Email Email = new Email(_ctx, _mattachment);
                            this.Close();
                            Utility.Envs.RegisterWindowForm(Email);
                            Envs.ShowForm(Email);
                        }

                    });
                });



                //_ok = true;

            }

            //do not use this.Close(), this function may keep parent window disable even after ths wondow is closed
            //this.Close();
           // this.DialogResult = true;
        }

    



    

        
        //private void SetGrid(VAdvantage.Controls.VDataGridView ctrl)
        //{
        //    //this.tabPage2.Controls.Add(this.vdgv);

        //    // vDataGridView1
        //    ctrl.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
        //    ctrl.DisplayGridRowNumber = false;
        //    ctrl.Dock = System.Windows.Forms.DockStyle.Fill;
        //    ctrl.Location = new System.Drawing.Point(3, 3);
        //    //ctrl.Name = "vdgrSentMail";
        //    ctrl.Size = new System.Drawing.Size(795, 423);
        //    ctrl.TabIndex = 0;

        //    CommonFunctions.SetDataGridPrperties(ctrl);
        //    ctrl.ColumnHeadersDefaultCellStyle.Font = new System.Drawing.Font("MS Sans Serif", 9, System.Drawing.FontStyle.Regular);
        //    ctrl.RowHeadersVisible = false;
        //    ctrl.DisplayGridRowNumber = false;
        //    ctrl.RowTemplate.Height = 18;
        //    ctrl.ReadOnly = true;
        //    // ctrl.CellDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.vdgv_CellDoubleClick);

        //    //Letter Attachment

        //    // vDataGridView1
        //    //this.vdgvLetterAttachment.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
        //    //this.vdgvLetterAttachment.DisplayGridRowNumber = false;
        //    //this.vdgvLetterAttachment.Dock = System.Windows.Forms.DockStyle.Fill;
        //    //this.vdgvLetterAttachment.Location = new System.Drawing.Point(3, 3);
        //    //this.vdgvLetterAttachment.Name = "vdgvLetterAttachment";
        //    //this.vdgvLetterAttachment.Size = new System.Drawing.Size(795, 423);
        //    //this.vdgvLetterAttachment.TabIndex = 0;

        //    //CommonFunctions.SetDataGridPrperties(vdgvLetterAttachment);
        //    //vdgvLetterAttachment.ColumnHeadersDefaultCellStyle.Font = new System.Drawing.Font("MS Sans Serif", 9, System.Drawing.FontStyle.Regular);

        //    //vdgvLetterAttachment.RowHeadersVisible = false;
        //    //vdgvLetterAttachment.DisplayGridRowNumber = false;
        //    ////vdgvLetterAttachment.GridColor = vdgvLetterAttachment.DefaultCellStyle.BackColor;
        //    //vdgvLetterAttachment.RowTemplate.Height = 18;
        //    //vdgvLetterAttachment.ReadOnly = true;
        //    // this.vdgvLetterAttachment.CellDoubleClick += new DataGridViewCellEventHandler(vdgvLetterAttachment_CellDoubleClick);

        //}

        //private void vdgv_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        //{
        //    //VAdvantage.Controls.VDataGridView ctrl = (VAdvantage.Controls.VDataGridView)sender;
        //    //if (e.RowIndex != -1 && e.ColumnIndex != 0)
        //    //{
        //    //    int MailAttachment_ID = Util.GetValueOfInt(ctrl.Rows[e.RowIndex].Cells["mailAttachment1_id"].FormattedValue);
        //    //    if (MailAttachment_ID == 0)
        //    //    {
        //    //        _mattachment = new MMailAttachment1(_ctx, _AD_Table_ID, _Record_ID, null);
        //    //    }
        //    //    else
        //    //    {
        //    //        _mattachment = new MMailAttachment1(_ctx, MailAttachment_ID, null);
        //    //    }


        //    //    //int size = _mattachment.GetEntryCount();
        //    //    //VAdvantage.Framework.Email emailText = new Email(_ctx, Msg.GetMsg(_ctx, "EMailSupport"), ctrl.Rows[e.RowIndex].Cells[Msg.GetMsg(Env.GetCtx(), "MailTo")].FormattedValue, vdgv.Rows[e.RowIndex].Cells[Msg.GetMsg(Env.GetCtx(), "Subject")].FormattedValue, vdgv.Rows[e.RowIndex].Cells["textmsg"].FormattedValue, _mattachment, true);
        //    //    //emailText.ShowDialog();

        //    //    //
        //    //    MailBox.ShowMailMessage oShowMailMsg = new VAdvantage.MailBox.ShowMailMessage(_mattachment);
        //    //    oShowMailMsg.ShowDialog();
        //    //}


        //}

        //private void vdgv_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        //{
        //    if (e.RowIndex == -1)
        //    {
        //        e.Graphics.DrawImage(Properties.Resources.Attachment16, 3, 3);
        //    }
        //}

        //private void vdgv_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        //{
        //    VAdvantage.Controls.VDataGridView ctrl = (VAdvantage.Controls.VDataGridView)sender;
        //    if (e.RowIndex == -1)
        //    {
        //        //e.Graphics.DrawImage(Properties.Resources.Attachment16, 3, 3);
        //    }
        //    else if (e.ColumnIndex == 0)
        //    {
        //        if (ctrl.Rows[e.RowIndex].Cells["isattachment"].Value != null)
        //        {
        //            string showImg = ctrl.Rows[e.RowIndex].Cells["isattachment"].Value.ToString();
        //            if (showImg == "Y")
        //            {

        //                e.Value = Env.GetImageIcon("Attachment16.gif");

        //            }

        //        }
        //    }
        //    if (ctrl.Rows[e.RowIndex].Cells["IsMailSent"].Value.ToString() == "N" && ctrl.Name != vdgvLetterAttachment.Name)
        //    {
        //        e.CellStyle.ForeColor = System.Drawing.Color.Red;
        //    }
        //}

        //private void vdgv_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        //{
        //    VAdvantage.Controls.VDataGridView ctrl = (VAdvantage.Controls.VDataGridView)sender;
        //    if (e.RowIndex != -1 && e.ColumnIndex != 0)
        //    {
        //        int MailAttachment_ID = Util.GetValueOfInt(ctrl.Rows[e.RowIndex].Cells["mailAttachment1_id"].FormattedValue);
        //        if (MailAttachment_ID == 0)
        //        {
        //            _mattachment = new MMailAttachment1(_ctx, _AD_Table_ID, _Record_ID, null);
        //        }
        //        else
        //        {
        //            _mattachment = new MMailAttachment1(_ctx, MailAttachment_ID, null);
        //        }


        //        //int size = _mattachment.GetEntryCount();
        //        //VAdvantage.Framework.Email emailText = new Email(_ctx, Msg.GetMsg(_ctx, "EMailSupport"), ctrl.Rows[e.RowIndex].Cells[Msg.GetMsg(Env.GetCtx(), "MailTo")].FormattedValue, vdgv.Rows[e.RowIndex].Cells[Msg.GetMsg(Env.GetCtx(), "Subject")].FormattedValue, vdgv.Rows[e.RowIndex].Cells["textmsg"].FormattedValue, _mattachment, true);
        //        //emailText.ShowDialog();
        //        if (ctrl.Name == vdgvLetterAttachment.Name)
        //        {
        //            VAdvantage.Framework.Email letter = new Email(_ctx, Msg.GetMsg(_ctx, "Letter"), _mattachment);
        //            letter.ShowDialog();
        //        }
        //        else
        //        {
        //            MailBox.ShowMailMessage oShowMailMsg = new VAdvantage.MailBox.ShowMailMessage(_mattachment);
        //            oShowMailMsg.ShowDialog();
        //        }

        //    }

        //}


        //private void vdgvLetterAttachment_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        //{
        //    if (e.RowIndex != -1 && e.ColumnIndex != 0)
        //    {
        //        int MailAttachment_ID = Util.GetValueOfInt(vdgvLetterAttachment.Rows[e.RowIndex].Cells["mailAttachment1_id"].FormattedValue);
        //        if (MailAttachment_ID == 0)
        //        {
        //            _mattachment = new MMailAttachment1(_ctx, _AD_Table_ID, _Record_ID, null);
        //        }
        //        else
        //        {
        //            _mattachment = new MMailAttachment1(_ctx, MailAttachment_ID, null);
        //        }
        //        VAdvantage.Framework.Email letter = new Email(_ctx, Msg.GetMsg(_ctx, "Letter"), vdgvLetterAttachment.Rows[e.RowIndex].Cells[Msg.GetMsg(Envs.GetContext(), "Address", true).ToString()].FormattedValue, vdgvLetterAttachment.Rows[e.RowIndex].Cells[Msg.GetMsg(Env.GetCtx(), "Subject")].FormattedValue, vdgvLetterAttachment.Rows[e.RowIndex].Cells["textmsg"].FormattedValue, _mattachment, false);
        //        letter.ShowDialog();
        //    }


        //}
        //private void vdgvLetterAttachment_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        //{

        //    if (e.RowIndex == -1)
        //    {
        //        e.Graphics.DrawImage(Properties.Resources.Attachment16, 3, 3);
        //    }
        //}
        //private void vdgvLetterAttachment_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        //{
        //    if (e.ColumnIndex == 0)
        //    {
        //        bool showImg = vdgvLetterAttachment.Rows[e.RowIndex].Cells["isattachment"].Value != DBNull.Value;
        //        if (showImg)
        //        {
        //            e.Value = Env.GetImageIcon("Attachment16.gif");
        //        }
        //        else
        //        {
        //            e.Value = Env.GetImageIcon("Tranparent.gif");
        //        }
        //    }
        //}


        //Appontment


        //private void vdgvApp_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        //{
        //    if (e.RowIndex != -1)
        //    {
        //        if (vdgvApp.Rows[e.RowIndex].Cells[0].Value != null || vdgvApp.Rows[e.RowIndex].Cells[0].Value != DBNull.Value)
        //        {
        //            new VAdvantage.Scheduler.cAppointment(Convert.ToInt32(vdgvApp.CurrentRow.Cells[0].Value));
        //        }
        //    }
        //}

        //private void vbtnOk_MouseDown(object sender, MouseEventArgs e)
        //{
        //    //CommonFunctions.SetButton(vbtnOk, CommonFunctions.ButtonType.OK, true);
        //}

        //private void vbtnOk_MouseUp(object sender, MouseEventArgs e)
        //{
        //    // CommonFunctions.SetButton(vbtnOk, CommonFunctions.ButtonType.OK, false);
        //}

        //private void vbtnCancel_MouseUp(object sender, MouseEventArgs e)
        //{
        //    //CommonFunctions.SetButton(vbtnCancel, CommonFunctions.ButtonType.Cancel, false);
        //}

        //private void vbtnCancel_MouseDown(object sender, MouseEventArgs e)
        //{
        //    //CommonFunctions.SetButton(vbtnCancel, CommonFunctions.ButtonType.Cancel, true);
        //}

    }
}

